<?php
namespace app\api\service\delivery\fengniao;

use app\api\service\delivery\PlatformInterface;
use app\api\service\delivery\fengniao\ApiService;
use think\exception\ValidateException;
use app\api\model\Order;
use think\facade\Log;

class FengniaoAdapter implements PlatformInterface
{

    public $ApiService;

    // 状态码
    const STATUS_ERROR = 0;
    const STATUS_SUCCESS = 200;
    const STATUS_APIERROR = 500;
    const STATUS_SIGN_ERROR = 1099;

    public static function statusList()
    {
        return [
            self::STATUS_ERROR => 'error',
            self::STATUS_SUCCESS => 'Success',
            self::STATUS_SIGN_ERROR => '签名错误',
            self::STATUS_APIERROR => '接口错误',
        ];
    }

    // 订单状态
    const STATUS_ORDER_DISPATCH = 20;
    const STATUS_ORDER_PICKUPING = 30;
    const STATUS_ORDER_DELIVERY = 40;
    const STATUS_ORDER_COMPLETED = 50;
    const STATUS_ORDER_CANCELLED = 60;

    public static function statusOrderList()
    {
        return [
            self::STATUS_ORDER_DISPATCH => '派单中',
            self::STATUS_ORDER_PICKUPING => '待取货',
            self::STATUS_ORDER_DELIVERY => '配送中',
            self::STATUS_ORDER_COMPLETED => '已完成',
            self::STATUS_ORDER_CANCELLED => '已取消',
        ];
    }


    /*
    * $config: 配置信息
    * $pro_dev: true正式域名 false测试域名
    */
    public function __construct(array $config)
    {
        $this->ApiService=new ApiService($config);
    }


// ------------------------------------具体实现方法-----------------------------------



    // 1.查询开通城市
    public function openCitiesLists($params=[])
    {
        $res = $this->ApiService->sendUnite('openCitiesLists');

        return $this->ApiService->returnUnite($res);
    }

    // 2.分页查询商户店铺
    public function queryAllStores($params=[])
    {
        try {
            validate([
                'pageNo'  => 'require', 
                'pageSize'  => 'require', 
                'pageSize'  => 'require', 
            ])->message([
                'pageNo.require'  => 'pageNo必须传递',   
                'pageSize.require'  => 'pageSize必须传递',   
                'pageSize.require'  => 'pageSize必须传递',   
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $data['storeName'] = $params['storeName'];
        $data['pageNo'] = $params['pageNo'];
        $data['pageSize'] = $params['pageSize'];
        $data = array_filter($data);

        $res = $this->ApiService->sendUnite('queryAllStores',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 4.查询城市可指定的交通工具
    public function optionalTravelWay($params=[])
    {
        try {
            validate([
                'cityId'  => 'require', 
            ])->message([
                'cityId.require'  => 'cityId必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $data['cityId'] = $params['cityId'];

        $res = $this->ApiService->sendUnite('optionalTravelWay',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 5.订单计费
    public function orderCalculate($params=[])
    {
        \think\facade\Log::info('闪送--订单计费--请求源参数--:' . json_encode($params));

        try {
            validate([
                'cityName'  => 'require', 
                'appointType'  => 'require', 
                'sender'  => 'require', 
                'receiverList'  => 'require', 
                'storeId'  => 'require', 
            ])->message([
                'cityName.require'  => 'cityName必须传递',   
                'appointType.require'  => 'appointType必须传递',   
                'sender.require'  => 'sender必须传递',   
                'receiverList.require'  => 'receiverList必须传递',   
                'storeId.require'  => 'storeId必须传递',   
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $data['city_name'] = $params['cityName']??'';
        $data['appoint_type'] =$params['appointType']??'';
        $data['appointment_date'] = $params['appointmentDate']??'';
        $data['store_id'] = $params['storeId']??'';
        $data['store_name'] = $params['storeName']??'';
        $data['travel_way'] = $params['travelWay']??'';
        $data['delivery_type'] = $params['deliveryType']??'';
        $data['pickup_pwd'] = $params['pickupPwd']??'';
        $data['lbs_type'] = $params['lbsType']??'';
        $data['sender'] = $params['sender']??'';
        $data['receiverList'] = $params['receiverList']??'';
        $data = array_filter($data);
        \think\facade\Log::info('闪送--订单计费--请求参数---:' . json_encode($data));
      
        $res = $this->ApiService->sendUnite('orderCalculate',$data);
        \think\facade\Log::info('闪送--订单计费--请求结果---:' . json_encode($res));

        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            $Order = new Order();
            $add = $Order->orderCreate($params,$res['data']);
            if($add['success']){
               return result_success('success',[]);
            }else{
               return result_error($add["msg"]??'保存失败');
            }
        }else{
           return result_error($res["msg"]??'请求失败');
        } 
    }

    // 6.提交订单
    public function orderPlace($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $data['issOrderNo'] = $params['issOrderNo']??'';
        \think\facade\Log::info('闪送--提交订单--请求参数---:' . json_encode($data));

        $res = $this->ApiService->sendUnite('orderPlace',$data);
        \think\facade\Log::info('闪送--提交订单--请求结果---:' . json_encode($res));

        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            $Order = new Order();
            $add = $Order->orderUpdate($res['data']);

            if($add['success']){
               return result_success('success',[]);
            }else{
               return result_error($add["msg"]??'保存失败');
            }
        }else{
           return result_error($res["msg"]??'请求失败');
        } 
    }

    // 7.订单加价
    public function addition($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
                'additionAmount'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
                'additionAmount.require'  => 'additionAmount必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        
        $data['issOrderNo'] = $params['issOrderNo'];
        $data['additionAmount'] =  $params['additionAmount'];
        \think\facade\Log::info('闪送--订单加价--请求参数---:' . json_encode($data));

        $res = $this->ApiService->sendUnite('addition',$data);
        \think\facade\Log::info('闪送--订单加价--请求结果---:' . json_encode($res));

        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            $Order = new Order();
            $add = $Order->additionSave($data);
            if($add['success']){
               return result_success('success',[]);
            }else{
               return result_error($add["msg"]??'保存失败');
            }
        }else{
           return result_error($res["msg"]??'请求失败');
        } 

    }

    // 8.查询订单详情
    public function orderInfo($params=[])
    {
         try {
            validate([
                'issOrderNo'  => 'require', 
                'thirdOrderNo'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
                'thirdOrderNo.require'  => 'thirdOrderNo必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        
        $data['issOrderNo'] = $params['issOrderNo'];
        $data['thirdOrderNo'] =  $params['thirdOrderNo'];

        $res = $this->ApiService->sendUnite('orderInfo',$data);

        $trailstr = '[{"longitude":120.255533,"latitude":30.211014,"datetime":"2025-06-05 16:36:24"},{"longitude":120.255605,"latitude":30.200589,"datetime":"2025-06-05 16:36:24"},{"longitude":120.260564,"latitude":30.200402,"datetime":"2025-06-05 16:36:24"}]';
        $res['data']['courier']['deliveryProcessTrail']= json_decode($trailstr,true);
        $res['data']['courier']['latitude']= '30.187791';
        $res['data']['courier']['longitude']= '120.259989';
        $res['data']['courier']['gcj02Trail']= json_decode($trailstr,true);
        $res['data']['courier']['gcj02Lat']= '30.187791';
        $res['data']['courier']['gcj02Lng']= '120.259989';
       
        return $this->ApiService->returnUnite($res);
    }

    // 9.查询闪送员位置信息
    public function courierInfo($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        
        $data['issOrderNo'] = $params['issOrderNo'];

        $res = $this->ApiService->sendUnite('courierInfo',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 10.查询订单续重加价金额
    public function calculateOrderAddWeightFee($params=[])
    {
         try {
            validate([
                'issOrderNo'  => 'require', 
                'weight'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
                'weight.require'  => 'weight必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        
        $data['issOrderNo'] = $params['issOrderNo'];
        $data['weight'] = $params['weight'];

        $res = $this->ApiService->sendUnite('calculateOrderAddWeightFee',$data);
       
        return $this->ApiService->returnUnite($res);
    }

    // 11.支付订单续重费用
    public function payAddWeightFee($params=[])
    {
         try {
            validate([
                'issOrderNo'  => 'require', 
                'payAmount'  => 'require', 
                'weight'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
                'payAmount.require'  => 'payAmount必须传递',    
                'weight.require'  => 'weight必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['issOrderNo'] = $params['issOrderNo'];
        $data['payAmount'] = $params['payAmount'];
        $data['weight'] = $params['weight'];
      
        $res = $this->ApiService->sendUnite('payAddWeightFee',$data);
       
        return $this->ApiService->returnUnite($res);
    }

    // 12.订单预取消
    public function preAbortOrder($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',       
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['issOrderNo'] = $params['issOrderNo'];
     
        $res = $this->ApiService->sendUnite('preAbortOrder',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 13.订单取消
    public function abortOrder($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
                'deductFlag'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',       
                'deductFlag.require'  => 'deductFlag必须传递',       
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['issOrderNo'] = $params['issOrderNo'];
        $data['deductFlag'] = $params['deductFlag'];

        $res = $this->ApiService->sendUnite('abortOrder',$data);


        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            $Order = new Order();
            $res['data']['orderNumber'] = $data['issOrderNo'];
            $res['data']['status'] = self::STATUS_ORDER_CANCELLED;
            $add = $Order->orderUpdate($res['data']);
            if($add['success']){
               return result_success('success',[]);
            }else{
               return result_error($add["msg"]??'保存失败');
            }
        }else{
           return result_error($res["msg"]??'请求失败');
        } 
    }

    // 14.确认物品送回
    public function confirmGoodsReturn($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',           
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['issOrderNo'] = $params['issOrderNo'];

        $res = $this->ApiService->sendUnite('confirmGoodsReturn',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 15.新增店铺，16.修改店铺
    public function storeOperation($params=[])
    {
        $param['storeName'] = request()->post('storeName/s','','strip_tags,htmlspecialchars');
        $param['cityName'] = request()->post('cityName/s', '', 'strip_tags,htmlspecialchars');
        $param['address'] = request()->post('address/s', '', 'strip_tags,htmlspecialchars');
        $param['addressDetail'] = request()->post('addressDetail/s', '', 'strip_tags,htmlspecialchars');
        $param['latitude'] = request()->post('latitude/s', '', 'strip_tags,htmlspecialchars');
        $param['longitude'] = request()->post('longitude/s', '', 'strip_tags,htmlspecialchars');
        $param['phone'] = request()->post('phone/s', '', 'strip_tags,htmlspecialchars');
        $param['goodType'] = request()->post('goodType/d', 0); // 默认值为0
        $param['operationType'] = request()->post('operationType/d', 1); // 默认值为1创建店铺，2更新店铺
        //修改店铺需要传递店铺ID
        if ($param['operationType'] == 2){
            $param['storeId'] = request()->post('storeId/d', 0); // 修改店铺必传店铺ID
            if (empty(['storeId'])){
               output_error('更新店铺时店铺ID不能为空');
            }
        }
        $param = array_filter($param);

        $res = $this->ApiService->sendUnite('storeOperation',$param);

        if (!empty($res['status']) && $res['status'] != self::STATUS_SUCCESS){
           output_success('success',$res);
        }

        if ($param['operationType'] == 1){
            $param['storeId'] = isset($res['data']) ? intval($res['data']) : 0;
        }
        $param['originShopId'] = request()->post('originShopId/s', '', 'strip_tags,htmlspecialchars');  //门店编码
        $param['contactName'] = request()->post('contactName/s', '', 'strip_tags,htmlspecialchars');
        $param['appId'] = request()->post('appid/s', '', 'strip_tags,htmlspecialchars');

        if (!empty($res['status']) && $res['status'] == self::STATUS_SUCCESS){
            $shop = new Shop();
            $res_shop = $shop->shopSave($param);
        }

        if (!empty($res_shop['status']) && $res_shop['status'] == 1){
           output_success('success',$res);
        }
       output_error('店铺操作失败', $res);
    }

    // 17.查询账号额度
    public function getUserAccount($params=[])
    {
        $res = $this->ApiService->sendUnite('getUserAccount');

       output_success('success',$res);
    }

    // 18.订单状态回调
    public function notify()
    {
        $param = request()->post();
        if(empty($param['issOrderNo'])){
            \think\facade\Log::error("订单号为空:".json_encode($param));
            return json_encode(["status"=>self::STATUS_SUCCESS,"msg"=>"","data"=>null]);
        }
        $param['orderNumber'] = $param['issOrderNo'];
        $orderdetail =Order::where('order_number', $param['issOrderNo'])->order('id', 'desc')->find();
        $store_id = $orderdetail['store_id'] ?? 0;
        if (!empty($store_id)){
            $notify_url = AppConfig::alias('m')
                ->where('store_id', $store_id)
                ->join('shop s','m.appid = s.appid')
                ->order('m.id', 'desc')
                ->value("notify_url");
        }

        if (empty($notify_url)){
            \think\facade\Log::error("回调地址不存在:".json_encode($param));
            return json_encode(["status"=>self::STATUS_SUCCESS,"msg"=>"","data"=>null]);
        }

        $this->curlPost($notify_url, $param);

        //更新配送员消息
        if (!empty($param['courier'])){
            $Courier = new Courier();
            $param['courier']['orderNumber'] = $param['issOrderNo'];
            if (!empty($orderdetail['courier_id'])){
                $param['courier']['orderNumber'] = $orderdetail['courier_id'];
            }
            $courier_res = $Courier->courierSave($param['courier']);
        }
        if (empty($courier_res['data'])){
            \think\facade\Log::error("配送员保存失败:".json_encode($param)."订单更新结果:".json_encode($courier_res));
        }
        //更新订单信息
        if (!empty($courier_res['data']) && !empty($orderdetail['courier_id'])){
            $param['courierId'] = $courier_res['data'];
        }

        $Order = new Order();
        $res_order = $Order->orderUpdate($param);
        if (empty($res_order['status'])){
            \think\facade\Log::error("订单更新失败:".json_encode($param)."订单更新结果:".json_encode($res_order));
            return json_encode(["status"=>self::STATUS_ERROR,"msg"=>"","data"=>null]);
        }
        return json_encode(["status"=>self::STATUS_SUCCESS,"msg"=>"","data"=>null]);
    }

    // 19.修改收件人手机号
    public function updateToMobile()
    {
        $param['issOrderNo'] = request()->post('issOrderNo/s','','strip_tags,htmlspecialchars');
        $param['thirdOrderNo'] = request()->post('thirdOrderNo/s','','strip_tags,htmlspecialchars');
        $param['newToMobile'] = request()->post('newToMobile/s','','strip_tags,htmlspecialchars');
        if(empty($param['issOrderNo']) || empty($param['thirdOrderNo']) || empty($param['newToMobile'])){
           output_error('参数不能为空');
        }

        $res = $this->ApiService->sendUnite('updateToMobile',$param);
        if (!empty($res['status']) && $res['status'] == self::STATUS_SUCCESS){
            $ReceiverInfo = new ReceiverInfo();
            $where = [];
            $where['order_number'] = $param['issOrderNo'];
            $where['third_order_no'] = $param['thirdOrderNo'];
            $phoneParam['to_mobile'] = $param['newToMobile'];
            $result = $ReceiverInfo->Save($phoneParam,$where);
            if ($result) {
                $this->outReturn(['status' => self::STATUS_SUCCESS, 'msg' => '修改收件人手机号成功', 'data' => $result]);
            } else {
                $this->outReturn(['status' => self::STATUS_SIGN_ERROR, 'msg' => '修改收件人手机号失败']);
            }
        }

       output_success('success',$res);
    }

    // 20.批量新增店铺
    public function addStores()
    {
        $storeList = request()->post('data/a',[],'strip_tags,htmlspecialchars');
        if (empty($storeList)){
           output_error('店铺列表不能为空');
        }

        $res = $this->ApiService->sendUnite('addStores',$storeList);

        $stores = [];
        $appid = request()->post('appid/s', '', 'strip_tags,htmlspecialchars');
        if (!empty($res['status']) && $res['status'] == self::STATUS_SUCCESS && !empty($res['data']['successList'])){
            foreach ($res['data']['successList'] as $store){
                $stores[$store['storeId']] = $store['dto'];
                $stores[$store['storeId']]['storeId'] = $store['storeId'];
                $stores[$store['storeId']]['contactName'] = $stores[$store['storeId']]['phone'] ?? '';
                $stores[$store['storeId']]['appId'] = $appid;

            }
            $shop = new Shop();
            $res_shop = $shop->shopListSave($stores);
        }
        if (!empty($res_shop['status']) && $res_shop['status'] == 1){
           output_success('success',$res);
        }
       output_error('店铺操作失败');
    }

    // 21.查询订单ETA
    public function orderEta()
    {
        $param['cityId'] = request()->post('cityId/d','','strip_tags,htmlspecialchars');
        $param['fromLat'] = request()->post('fromLat/f',0,'strip_tags,htmlspecialchars');
        $param['fromLng'] = request()->post('fromLng/f',0,'strip_tags,htmlspecialchars');
        $param['toLat'] = request()->post('toLat/f',0,'strip_tags,htmlspecialchars');
        $param['toLng'] = request()->post('toLng/f',0,'strip_tags,htmlspecialchars');

        if(empty($param['cityId']) || empty($param['fromLat']) || empty($param['fromLng']) || empty($param['toLat']) || empty($param['toLng'])){
           output_error('参数不能为空');
        }

        $res = $this->ApiService->sendUnite('orderEta',$param);

       output_success('success',$res);
    }

    // 22.订单追单
    public function appendOrder()
    {
        $param['orderNumber'] = request()->post('orderNumber/s','','strip_tags,htmlspecialchars');
        $param['appendOrderNumber'] = request()->post('appendOrderNumber/s','','strip_tags,htmlspecialchars');
        if(empty($param['orderNumber']) || empty($param['appendOrderNumber'])){
           output_error('参数不能为空');
        }

        $res = $this->ApiService->sendUnite('appendOrder',$param);

       output_success('success',$res);
    }

    // 23.查询是否支持尊享送
    public function qualityDeliverySwitch()
    {
        $param['cityName'] = request()->post('cityName/s','','strip_tags,htmlspecialchars');
        if($param['cityName'] == ''){
           output_error('城市名字不能为空');
        }

        $res = $this->ApiService->sendUnite('qualityDeliverySwitch',$param);

       output_success('success',$res);
    }

    // 24.查询尊享送达成状态
    public function qualityDeliveryStatus()
    {
        $param['issOrderNo'] = request()->post('issOrderNo/s','','strip_tags,htmlspecialchars');
        if($param['issOrderNo'] == ''){
           output_error('闪送订单号不能为空');
        }

        $res = $this->ApiService->sendUnite('qualityDeliveryStatus',$param);

       output_success('success',$res);
    }

}